<!--
 * @Version: 1.0
 * @Autor:
 * @Date: 2021-03-10 16:57:07
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-09-13 14:18:19
 * @Description:
-->
<template>
  <el-card class="app-container content_box" shadow="always">
    <div>
      <!-- title -->
      <!-- <div class="header_title_box">
        <h2>货代公司管理</h2>
      </div> -->
      <!-- <div class="select_form_box">
        <div class="filter-container">
          <el-input v-model="queryParam.name" size="small" placeholder="货代公司" class="select250 mr16" @keyup.enter.native="handleSearch" />
          <el-select v-model="queryParam.status" size="small" placeholder="请选择状态" class="select250 mr16" clearable @change="handleSearch">
            <el-option v-for="(item, index) in option" :key="index" :value="item.value" :label="item.label" />
          </el-select>
        </div>
      </div> -->
      <form-selections :is-active="isActive" :items="formItems" :query-param.sync="queryParam" display="block" @handleSearch="handleSearch" />
      <div class="select_flex">
        <div class="operation_button_box">
          <el-button v-action="'LforwarderFreight@save'" icon="el-icon-circle-plus" size="small" type="success" @click="handleCreate()">新增货代公司</el-button>
          <el-button v-action="'LforwarderFreight@disable'" :disabled="selectedIds.length?false:true" size="small" type="danger" @click="handleDisable()">禁用</el-button>
          <el-button v-action="'LforwarderFreight@enable'" :disabled="selectedIds.length?false:true" size="small" type="primary" @click="handleEnable()">启用</el-button>
        </div>
        <div>
          <el-button size="small" type="primary" class="filter-item search" icon="el-icon-search" @click="handleSearch">
            搜索
          </el-button>
          <el-button size="small" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
        </div>
      </div>
      <div v-loading="loading">
        <el-table ref="multipleTable" :data="data" tooltip-effect="dark" style="width: 100%" :max-height="screenHeigh" border fit @selection-change="handleSelectMulti">
          <el-table-column align="center" type="selection" width="55" />
          <el-table-column label="操作" align="center" fixed width="200px">
            <template slot-scope="scope">
              <span v-if="scope.row.is_status===2" v-action="'LforwarderFreight@update'" class="edit_style" @click="handleUpdateNew(scope.row)">编辑</span>
              <span v-if="scope.row.is_status===2" v-action="'LforwarderFreight@delete'" class="delete_style" @click="handleDelete(scope.row.id)">删除</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="货代公司代码" prop="code" />
          <el-table-column align="center" label="货代公司" prop="name" width="280" />
          <el-table-column align="center" label="结算周期（天）" prop="settlement_cycle" />
          <el-table-column align="center" prop="is_status" label="状态">
            <template slot-scope="scope">
              {{ scope.row.is_status===1?'启用':'禁用' }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="creator_name" label="创建人" width="150" />
          <el-table-column align="center" prop="created_at" label="创建时间" width="165" />
          <el-table-column align="center" prop="update_name" label="修改人">
            <template slot-scope="scope">
              {{ scope.row.update_name?scope.row.update_name:'-' }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="updated_at" label="更新时间" width="165" />
        </el-table>
        <el-pagination v-if="paginate.total > 0" class="pagination_box" background :current-page="paginate.current" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
      <!-------- 回到顶部 ------------>
      <el-backtop :visibility-height="60">
        <i class="el-icon-caret-top" />
      </el-backtop>
      <el-dialog :center="true" :title="title" :visible.sync="formVisible" width="950px" @close="handleCancelSelf">
        <el-form :ref="formName" :model="formFieldsData" :rules="rules" inline class="dialog-form-expand2">
          <div class="header_title_box">
            <h2>货代公司信息</h2>
          </div>
          <el-form-item label="货代公司代码" :label-width="formLabelWidth" prop="code">
            <el-input v-model.trim="formFieldsData.code" placeholder="请输入货代公司代码" oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')" autocomplete="off" clearable style="width:247px" />
          </el-form-item>
          <el-form-item label="货代公司" :label-width="formLabelWidth" prop="name">
            <el-input v-model.trim="formFieldsData.name" placeholder="请输入货代公司" autocomplete="off" clearable style="width:247px" />
          </el-form-item>
          <el-form-item label="结算周期" :label-width="formLabelWidth" prop="settlement_cycle">
            <el-input v-model.trim="formFieldsData.settlement_cycle" placeholder="请输入结算周期" autocomplete="off" clearable>
              <template slot="append">天</template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注说明" :label-width="formLabelWidth" prop="remarks">
            <el-input v-model="formFieldsData.remarks" type="textarea" autosize placeholder="请输入备注说明" show-word-limit autocomplete="off" clearable style="width:247px" />
          </el-form-item>
        </el-form>
        <div class="header_title_box">
          <h2 style="margin-right:50px">
            账户信息
          </h2>
          <div>
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="addField">新增</el-button>
          </div>
        </div>
        <div>
          <el-form ref="formData" :rules="model.rules" :model="model" class="dialog-form-expand3">
            <el-table :data="model.fields" tooltip-effect="dark" style="width: 100%" border>
              <el-table-column align="center" label="操作" width="150">
                <template slot-scope="field">
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteField(field.row)" />
                  <el-button v-if="field.row.disabled" type="primary" size="mini" icon="el-icon-edit" @click="editOpen(field.$index)" />
                  <el-button v-if="!field.row.disabled && formFieldsData.id" type="primary" size="mini" @click="save(formFieldsData.id, field.row, field.$index, 'lfCurrency')">保存</el-button>
                </template>
              </el-table-column>
              <el-table-column align="center" label="币别">
                <template slot-scope="field">
                  <el-form-item :prop="'fields.' + field.$index + '.currency_data'" :rules="model.rules.currency_data">
                    <el-select v-model="field.row.currency_data" :disabled="field.row.disabled" size="mini" filterable clearable placeholder="请输入关键词">
                      <el-option v-for="item in optionsCurrency" :key="item.value" :label="`${item.label}(${item.source_code})`" :value="item.value" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="开户行">
                <template slot-scope="field">
                  <el-form-item :prop="'fields.' + field.$index + '.bank_name'" :rules="model.rules.bank_name">
                    <el-input v-model.trim="field.row.bank_name" :disabled="field.row.disabled" size="mini" placeholder="输入开户行" autocomplete="off" clearable />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="银行账号">
                <template slot-scope="field">
                  <el-form-item :prop="'fields.' + field.$index + '.bank_number'" :rules="model.rules.bank_number">
                    <el-input v-model.trim="field.row.bank_number" :disabled="field.row.disabled" size="mini" placeholder="输入银行账号" autocomplete="off" clearable />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer-center">
          <el-button @click="handleCancelSelf">取 消</el-button>
          <el-button type="primary" @click="handleSubmitNew">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import formOperate from '@/layout/mixin/formOperate'
import {
  action
} from '@/directive/permission/index.js' // 权限判断指令
import {
  currencyAll
} from '@/utils/publicData'
import { validChineseOrs } from '@/utils/validate'
import cacheList from '@/layout/mixin/cacheList'
export default {
  name: 'BasicsLforwarders',
  directives: {
    action
  },
  mixins: [formOperate, cacheList],
  data() {
    return {
      otherHeight: 365,
      componentName: 'BasicsLforwarders',
      url: '/LforwarderFreight',
      queryParam: {
        status: '',
        name: '',
        type: 2,
        page: 1,
        limit: 10
      },
      defaultQueryParam: ['type'],
      option: [{
        value: 2,
        label: '禁用'
      },
      {
        value: 1,
        label: '启用'
      }
      ],
      loading: false,
      formVisible: false,
      formFieldsData: {
        type: 2, // 1：货代，2：货代
        code: '', // 店铺编号
        name: '',
        settlement_cycle: '',
        remarks: ''
      },
      formItems: [
        {
          label: '货代公司',
          key: 'name',
          type: 'input',
          placeholder: '请输入货代公司'
        },
        {
          label: '状态',
          key: 'status',
          type: 'select',
          placeholder: '请选择状态',
          options: [
            {
              value: 2,
              label: '禁用'
            },
            {
              value: 1,
              label: '启用'
            }
          ]
        }
      ],
      formName: 'lforwarders',
      formLabelWidth: '120px',
      rules: {
        code: [
          { required: true, message: '请输入货代公司代码', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              if (validChineseOrs(value)) {
                callback(new Error('代码须是字母，数字，非空字符组成'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          },
          { max: 30, message: '货代公司代码须在30个字符以内', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入货代公司名称', trigger: 'blur' },
          { max: 50, message: '货代公司名称须在50个字符以内', trigger: 'blur' }
        ],
        settlement_cycle: [
          { required: true, message: '请输入结算周期', trigger: 'blur' },
          { pattern: /^[0-9]*$/, message: '只能输入数字', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              if (value > 1000) {
                callback(new Error('结算周期不能大于1000天'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      model: {
        rules: {
          currency_data: { required: true, message: '必填字段', trigger: 'blur' },
          bank_name: { required: true, message: '必填字段', trigger: 'blur' },
          bank_number: [
            { required: true, message: '请输入银行账号', trigger: 'blur' },
            { pattern: /^[0-9a-zA-Z]*$/, message: '银行账号必须为数字或字母组成', trigger: 'blur' },
            { max: 50, message: '银行账号必须在50个字符以内', trigger: 'blur' }
          ]
        },
        fields: [this.getColumn()]
      },
      optionsCurrency: []
    }
  },
  created() {
    const vm = this
    currencyAll().then((data) => {
      vm.optionsCurrency = data
      console.log('========vm.optionsCurrency=====', vm.optionsCurrency)
    })
  },
  methods: {
    beforeCreate() {
      this.formFieldsData.id = null
    },
    // 关闭弹窗处理函数
    handleCancelSelf() {
      const vm = this
      vm.formVisible = false
      vm.formFieldsData.code = ''
      vm.formFieldsData.name = ''
      vm.formFieldsData.settlement_cycle = ''
      vm.formFieldsData.remarks = ''
      vm.model.fields = [vm.getColumn()]
      vm.$refs.formData.clearValidate()
    },
    handleUpdateNew(data) {
      this.$http.get(`LforwarderFreight/${data.id}`).then(res => {
        const dataObj = res.data
        this.formFieldsData = dataObj
        this.model.fields = dataObj.userList.map((arr) => {
          arr.disabled = true
          arr.currency_data = arr.currency_id + ',' + arr.target_name
          return arr
        })
        this.formVisible = true
      })
    },
    handleSubmitNew() {
      this.$refs['lforwarders'].validate((valid) => {
        if (valid) {
          // 编辑
          if (this.formFieldsData.id) {
            this.$http.put(`LforwarderFreight/${this.formFieldsData.id}`, this.getData()).then(response => {
              if (response.code === 10000) {
                this.$message.success('编辑成功')
                this.formVisible = false
                this.handleRefresh()
              } else {
                this.$message.error(response.message)
              }
            })
          } else {
            // 判断个人信息
            this.$refs['formData'].validate((validSon) => {
              // 添加
              if (validSon) {
                this.$http.post('LforwarderFreight', this.getData()).then(response => {
                  if (response.code === 10000) {
                    this.$message.success('添加成功')
                    this.formVisible = false
                    this.handleRefresh()
                  } else {
                    this.$message.error(response.message)
                  }
                })
              }
            })
          }
        }
      })
    },
    // 获取添加参数组合
    getData() {
      const data = Object.assign({}, this.formFieldsData)
      delete data.updated_at
      delete data.created_at
      // data['is_status'] = 1
      if (this.model.fields) {
        const dataArr = this.model.fields.map((arr) => {
          arr.currency_arr = arr.currency_data.split(',')
          return {
            currency_id: arr.currency_arr[0],
            target_name: arr.currency_arr[1],
            bank_name: arr.bank_name,
            bank_number: arr.bank_number
          }
        })
        data['account_data'] = JSON.stringify(dataArr)
      }
      return data
    },
    // 数据列表
    getColumn() {
      return {
        'currency_data': '',
        'bank_name': '',
        'bank_number': ''
      }
    },
    list() {
      this.senderList()
    },
    // 寄件人信息列表
    senderList() {
      const vm = this
      const data = {
        limit: 100,
        page: 1,
        company_id: this.formFieldsData.id
      }
      vm.$http.get('lfCurrency', {
        params: data
      }).then((res) => {
        if (res.code === 10000) {
          this.model.fields = res.data.map((arr) => {
            arr.disabled = true
            arr.currency_data = arr.currency_id + ',' + arr.target_name
            return arr
          })
        }
      })
    }
  }
}

</script>

<style lang="scss" scoped>
</style>
